package com.team.teamuserservice.websocket.service;

import com.team.teamuserservice.annotation.WebsocketMessageType;
import com.team.teamuserservice.entity.dto.MerchantToUser;
import com.team.teamuserservice.entity.dto.WebsocketMessage;
import com.team.teamuserservice.uitls.MessageType;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

import static com.team.teamuserservice.websocket.RescueWebsocketHandler.userSessionMap;

@Component
@WebsocketMessageType(MessageType.RESCUE)
public class MerchantMessageHandler implements MessageHandler {
    @Override
    public void handleMessage(WebSocketSession session, WebsocketMessage message) throws IOException {
        //商家接收到了用户发来的救援信息 , 并通过acceptRescue抢单成功 , 这时候前端商家就可以返回自己的信息给用户了
        //先解析一下数据
        MerchantToUser merchantToUser = (MerchantToUser) message.getMessage();
        
        if (merchantToUser == null || merchantToUser.getUserId() == null) {
            return;
        }
        
        //获取用户session
        WebSocketSession userSession = userSessionMap.get(merchantToUser.getUserId());
        
        //发送消息给用户 , 这样前端用户就接受到了商家的信息 , 等待被救援就可以
        if (userSession != null && userSession.isOpen()) {
            userSession.sendMessage(new TextMessage(merchantToUser.getMerchantId().toString()));
        }
    }
}
